import zqdb.strategy as zqdb

class IcebergAlgo(zqdb.Strategy):
    """"""

    # 这里是默认设置，其中input是用户可以通过设置界面修改的入参
    default_setting = {
        'type':'算法',
        'name':'冰山算法',
        'desc':'冰山算法',
        'trigger':zqdb.TRIGGER_TYPE.MARKET,
        'input':{
            "direction_type": zqdb.DIRECTION_TYPE.LONG,
            "order_type": zqdb.ORDER_TYPE.LIMIT,
            "price": 0.0,
            "volume": 0.0,
            "display_volume": 0.0
        }
    }

    # 构造函数，外部需要传入setting设置，用户可以在构造函数里关联计算数据/指标等
    def __init__(
        self,
        setting: dict
    ):
        """Constructor"""
        super().__init__(setting)
        input = setting["input"]
        self.direction = input["direction_type"]
        self.type = input["order_type"]
        self.price = input["price"]
        self.volume = input["volume"]
        self.display_volume = input["display_volume"]
        self.orderid = ""
        self.traded = 0

    # 启动时调用
    def on_start(self):
        """"""
        pass

    # 停止时调用
    def on_stop(self):
        """"""
        pass
   
    # 计算函数，当关联的计算数据/指标等更新时就会被调用，策略算法可以调用交易相关函数
    def on_calc(self, code):
        """"""
        # 策略算法请在这里编写...

        user = self.user

        # If order already finished, just send new order
        if not self.orderid:
            order_volume = self.volume - self.traded
            order_volume = min(order_volume, self.display_volume)
            if order_volume > 0:
                self.orderid = self.order_send(code, self.direction, self.type, self.price, order_volume)
            else:
                # 停止算法
                self.stop() 
            
        # Otherwise check for cancel
        else:
            order = zqdb.Order(user, self.orderid)
            if self.direction == zqdb.DIRECTION_TYPE.LONG:
                if code.Ask1 <= self.price:
                    self.cancel_order(order)
                    self.orderid = ""
                    zqdb.LogInfo(u"最新Tick卖一价，低于买入委托价格，之前委托可能丢失，强制撤单")
            else:
                if code.Bid1 >= self.price:
                    self.cancel_order(order)
                    self.orderid = ""
                    zqdb.LogInfo(u"最新Tick买一价，高于卖出委托价格，之前委托可能丢失，强制撤单")

